package io.github.lee.jel.ui.main.home

import android.app.Application
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.jel.R
import io.github.lee.jel.domain.po.JellyfinSession
import io.github.lee.jel.err.ResponseFailException
import io.github.lee.jel.global.di.http.HttpModule
import io.github.lee.jel.global.session
import io.github.lee.jel.manager.JellyfinSessionManager
import io.github.lee.jel.manager.JellyfinSessionWatcher
import io.github.lee.jel.repository.ItemRepository
import io.github.lee.jel.repository.UserRepository
import io.github.lee.jel.repository.query.QueryImageTypes
import javax.inject.Inject

@HiltViewModel
class HomeVM @Inject constructor(
    application: Application,
    private val repo: UserRepository,
    private val itemRepo: ItemRepository,
) : BaseViewModel(application) {
    val addServerClickLiveData = MutableLiveData(false)
    val homeLiveData = MutableLiveData<HomeShowData>()

    private val sessionWatcher = object : JellyfinSessionWatcher {
        override fun onSessionChange(session: JellyfinSession) {
            sync(session)
        }

        override fun onSessionDelete(session: JellyfinSession?) {
            super.onSessionDelete(session)
            if (mContext.session?.address == session?.address) {
                init()
            }
        }
    }

    init {
        init()
    }

    fun init() {
        val session = mContext.session
        if (null != session) {
            success()
            HttpModule.resetNetwork(session)
            sync(session)
        } else {
            empty()
        }
    }


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        JellyfinSessionManager.registerWatcher(sessionWatcher)

    }

    override fun onDestroy(owner: LifecycleOwner) {
        JellyfinSessionManager.unregisterWatcher(sessionWatcher)
    }
    //===Desc:=============================================================

    fun gotoAddSever() {
        addServerClickLiveData.postValue(true)
    }


    fun sync(session: JellyfinSession, showProgress: Boolean = true) {
        launchResult(
            block = {
                if (showProgress) showProgress(getString(R.string.txt_start_syncing_folder), false)
                // 同步Views
                val viewsData = repo.views(session.userId)
                if (!viewsData.isSuccess) {
                    throw ResponseFailException(viewsData)
                }
                val views = viewsData.data


                if (showProgress) showProgress(getString(R.string.txt_start_syncing_playing), false)
                // 同步正在观看的
                val imageType =
                    listOf(QueryImageTypes.Backdrop, QueryImageTypes.Primary, QueryImageTypes.Thumb)
                val playingData = itemRepo.playingList(session.userId, enableImageTypes = imageType)
                if (!playingData.isSuccess) {
                    throw ResponseFailException(playingData)
                }
                val playing = playingData.data

                val folders = views?.items
                val classifyList = mutableListOf<Classify>()
                if (!folders.isNullOrEmpty()) {
                    folders.forEach {
                        if (showProgress) showProgress(
                            getString(
                                R.string.txt_start_syncing,
                                it.name
                            ), false
                        )
                        val imgType = listOf(
                            QueryImageTypes.Backdrop,
                            QueryImageTypes.Primary,
                            QueryImageTypes.Thumb
                        )
                        val latestData = itemRepo.latest(
                            session.userId, it.id,
                            enableImageTypes = imgType
                        )
                        if (!latestData.isSuccess) {
                            throw ResponseFailException(latestData)
                        }
                        val list = latestData.data
                        if (!list.isNullOrEmpty()) {
                            classifyList.add(
                                Classify(
                                    getString(R.string.txt_start_latest, it.name),
                                    list
                                )
                            )
                        }
                    }
                }

                homeLiveData.postValue(HomeShowData(playing?.items, classifyList))


            },
            error = {
                it?.printStackTrace()
                error(it)
                hideProgress()
            }
        ) {
            hideProgress()
        }
    }
}